<?php

/**
 * BH MEDIA
 * @author Ha Anh Man - manphp@binhhoang.com
 * @version 1.0
 * @package JobSearch
 * @copyright 2012
 * 
 */
class PeopleController extends BackendController {

    public function actionIndex() {
        $data = array();
        $where = '';

        $condition = new CDbCriteria();
        $condition->condition = $where;
        $condition->select = 'COUNT(id)';
        $item_count = User::model()->count($condition);

        $condition = new CDbCriteria();
        $condition->condition = $where;
        $condition->order = 'id DESC';

        $page_size = 20;
        $pages = new CPagination($item_count);
        $pages->setPageSize($page_size);
        $pages->applyLimit($condition);  // the trick is here!

        $data['listItem'] = User::model()->findAll($condition);
        $roles = Role::model()->findAll();
        $data['role'] = array();
        if (!empty($roles)) {
            foreach($roles as $item) {
                $data['role'][$item->id] = $item->role;
            }
        }
        $this->render('index', array(
            'data' => $data,
            'item_count' => $item_count,
            'page_size' => $page_size,
            'pages' => $pages,
        ));
    }

    public function actionAdd() {
        $data = array();
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ($this->validateForm()) {
                $roles = $_POST['role'];
                $u = new User();
                $u->email = trim($_POST['email']);
                $u->password = md5(trim($_POST['password']));
                $u->status = intval($_POST['status']);
                $u->register_time = time();
                if (!empty($roles)) {
                    $u->role = implode(',', $roles);
                }
                $u->save();
                $uid = $u->id;
                if (!empty($roles)) {
                    $query = "INSERT INTO {{user_role}} (uid, role_id) VALUES ";
                    foreach ($roles as $role_id) {
                        $query .= "(" . $uid . ", " . $role_id . "),";
                    }
                    $query = trim($query, ',');
                    $command = Yii::app()->db->createCommand($query);
                    $command->execute();
                }
                createMessage('Tạo mới người dùng <strong>' . $u->email . '</strong> thành công');
                $this->redirect(array('people/index'));
            } else {
                $data['user'] = $_POST;
                $data['user_role'] = empty($_POST['role']) ? array() : $_POST['role'];
            }
        }
        $data['user_role'] = array();
        $data['roles'] = Role::model()->findAll();
        $this->render('form', array('data' => $data));
    }

    public function actionEdit() {
        $data = array();
        $id = $_GET['uid'];
        $user = User::model()->findByPk($id);
        $data['user_role'] = array();
        if (empty($user)) {
            createMessage('Không tìm thấy nội dung yêu cầu', 'errormsg');
            $this->redirect(array('people/index'));
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ($this->validateForm()) {
                $roles = $_POST['role'];
                $user->email = trim($_POST['email']);
                if (!empty($roles)) {
                    $user->role = implode(',', $roles);
                }
                if (!empty($_POST['password'])) {
                    $user->password = md5(trim($_POST['password']));
                }
                $user->status = intval($_POST['status']);
                $user->save();
                if (!empty($roles)) {
                    //xoa role cua
                    UserRole::model()->deleteAll('uid = ' . $id);

                    //add role moi
                    $query = "INSERT INTO {{user_role}} (uid, role_id) VALUES ";
                    foreach ($roles as $role_id) {
                        $query .= "(" . $id . ", " . $role_id . "),";
                    }
                    $query = trim($query, ',');
                    $command = Yii::app()->db->createCommand($query);
                    $command->execute();
                }
                createMessage('Sửa người dùng <strong>' . $user->email . '</strong> thành công');
                $this->redirect(array('people/index'));
            } else {
                $data['user'] = $_POST;
                $data['user_role'] = empty($_POST['role']) ? array() : $_POST['role'];
            }
        } else {            
            $user_role = UserRole::model()->findAll('uid = ' . $id);
            foreach ($user_role as $r) {
                $data['user_role'][] = $r->role_id;
            }
        }
        $data['roles'] = Role::model()->findAll();
        $data['user'] = $user->attributes;
        $this->render('form', array('data' => $data));
    }

    private function validateForm() {
        $pass_form = true;

        $email = $_POST['email'];
        $password = $_POST['password'];
        $re_password = $_POST['re_password'];
        $status = $_POST['status'];
        $action = $this->action->id;
        $messages = array();
        $cmail = new CEmailValidator();
        if (empty($email)) {
            $messages[] = 'Vui lòng nhập email';
        } elseif (!$cmail->validateValue($email)) {
            $messages[] = 'Email <strong>' . $email . '</strong> không đúng định dạng';
        } else {
            $cond = new CDbCriteria();
            $cond->condition = 'email = :email';
            if ($action == 'edit') {
                $id = $_GET['uid'];
                $cond->condition .= ' AND id <> ' . $id;
            }
            $cond->params = array(':email' => $email);
            $user = User::model()->find($cond);
            if (!empty($user)) {
                $messages[] = 'Email <strong>' . $email . '</strong> đã tồn tại';
            }
        }

        if ($action == 'add') {
            if (empty($password)) {
                $messages[] = 'Vui lòng nhập mật khẩu';
            } elseif (!isset($password[5])) {
                $messages[] = 'Mật khẩu phải lớn hơn 6 ký tự';
            } elseif ($re_password != $password) {
                $messages[] = 'Xác nhận mật khẩu không đúng';
            }
        }
        
        if ($action == 'edit' && !empty($password)) {
            if (!isset($password[5])) {
                $messages[] = 'Mật khẩu phải lớn hơn 6 ký tự';
            } elseif ($re_password != $password) {
                $messages[] = 'Xác nhận mật khẩu không đúng';
            }
        }
        
        if (!empty ($messages)) {
            createMessage($messages, 'errormsg');
            $pass_form = false;
        }
        
        return $pass_form;
    }

}